import { trim, isEmpty } from 'lodash';
import { Op } from 'sequelize';
import BaseController from './base';
import CountryModel from '../models/country';
import ContinentModel from '../models/continent';

// order docs https://sequelize.org/docs/v6/core-concepts/model-querying-basics/
class CountryController extends BaseController {
  getModel() {
    return CountryModel;
  }

  /**
   * 解析查询条件
   * @returns {Object}
   */
  getFindWhere(req) {
    const {
      code, name, continent_id, disabled
    } = req.query;
    const where = {};

    if (trim(code)) {
      where.code = { [Op.like]: `%${trim(code)}%` };
    }

    if (trim(name)) {
      where.name = { [Op.like]: `%${trim(name)}%` };
    }

    if (continent_id) {
      where.continent_id = continent_id;
    }

    if (disabled === 'Y') {
      where.disabled = true;
    }
    else if (disabled === 'N') {
      where.disabled = false;
    }

    return { where: isEmpty(where) ? undefined : where };
  }

  getInclude() {
    return {
      include: [{
        model: ContinentModel,
        as: 'continent',
        attributes: ['id', 'code', 'name']
      }]
    };
  }

  async findOne(req, res, next) {
    try {
      const { id } = req.params;
      const model = this.getModel();
      const data = await model.findOne({
        where: { id },
        include: [{
          model: ContinentModel,
          as: 'continent',
          required: true,
          attributes: ['id', 'code', 'name', 'disabled']
        }],
        rejectOnEmpty: new Error('数据不存在')
      });
      res.sendOk(data);
    }
    catch (e) {
      next(e);
    }
  }
}

export default new CountryController();
